package com.chebaohui.iqs.sign;

import java.security.MessageDigest;

/**
 * 签名工具类
 * 
 * @author regas
 *
 */
public class SignUtil {

	/**
	 * 签名方法
	 * 
	 * @param org
	 *            需签名字符
	 * @param channel
	 *            渠道代码
	 * @return
	 */
	public static String encryption(String org, String channel) {
		if (null == org || "".equals(org.trim()))
			return "false";
		org += "&" + channel;
		return MD5Encode(org);
	}

	/**
	 * 签名验证方法
	 * 
	 * @param org
	 *            需签名字符
	 * @param sign
	 *            签名字段
	 * @param channel
	 *            渠道代码
	 * @return
	 */
	public static boolean decrypted(String org, String sign, String channel) {
		if (null == org || null == sign || "".equals(org.trim()) || "".equals(sign.trim()))
			return false;
		return encryption(org, channel).equals(sign);
	}

	/**
	 * 加密方法
	 * 
	 * @param origin
	 *            加密字符
	 * @return
	 */
	private static String MD5Encode(String origin) {
		String resultString = null;
		try {
			resultString = origin;
			MessageDigest md = MessageDigest.getInstance("MD5");
			resultString = byteArrayToHexString(md.digest(resultString.getBytes("UTF-8")));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return resultString;
	}

	private static String byteArrayToHexString(byte[] b) {
		StringBuilder resultSb = new StringBuilder();
		for (byte aB : b) {
			resultSb.append(byteToHexString(aB));
		}
		return resultSb.toString();
	}

	private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d",
			"e", "f" };

	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0) {
			n = 256 + n;
		}
		int d1 = n / 16;
		int d2 = n % 16;
		return hexDigits[d1] + hexDigits[d2];
	}

}
